﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;


namespace Common
{
    public class ConFactory
    {

        public static string MsSqlConStr
        {
            get;set;
        }

        /// <summary>
        ///  获取当前的链接对象Con(使用完释放了一个Con后，才重新生产新的Con。不适用于异步编程async)
        /// </summary>
        public static IDbConnection GetMsSqlCon(string sqlConnectionString = "")
        {
            //IDbConnection con = HttpContext.Current.Items["currentCon"] as IDbConnection;

            //if ( (con == null) || (con.State == ConnectionState.Closed) )
            //{
            //    if (string.IsNullOrEmpty(sqlConnectionString))
            //    {
            //        MsSqlConStr = ConfigurationManager.ConnectionStrings["MsSqlConStr"].ConnectionString;//IIS初始化时，内存中生成一份配置文件的对象，后期读取是从内存中读取，并非再次读文件
            //    }
            //    else
            //    {
            //        MsSqlConStr = sqlConnectionString;
            //    }
            //    con = new SqlConnection(MsSqlConStr);
            //    con.Open();

            //    HttpContext.Current.Items.Remove("currentCon");
            //    HttpContext.Current.Items.Add("currentCon",con);
            //}

            //return con;

            if (string.IsNullOrEmpty(sqlConnectionString))
            {
                MsSqlConStr = ConfigurationManager.ConnectionStrings["MsSqlConStr"].ConnectionString;//IIS初始化时，内存中生成一份配置文件的对象，后期读取是从内存中读取，并非再次读文件
            }
            else
            {
                MsSqlConStr = sqlConnectionString;
            }
            IDbConnection con = new SqlConnection(MsSqlConStr);
            con.Open();

            return con;
        }

        public static IDbConnection GetMsSqlConByUidAndPassword(string uid,string password)
        {
            StringBuilder sb = new StringBuilder(ConfigurationManager.ConnectionStrings["MsSqlConStr"].ConnectionString);
            MsSqlConStr=sb.Replace("@UID",uid).Replace("@Password",password).ToString();
            SqlConnection conn = new SqlConnection(MsSqlConStr);
            conn.Open();

            return conn;
        }

    }
}
